/*
 * @Date: 2021-11-01 11:03:07
 * @information: home数据业务
 */
import { ref, onMounted, reactive, toRefs } from "vue";
import api from "@/api/base";
import moment from "moment";
import { addFormInterface } from "@/interfaces/base";
import {useStore} from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from 'element-plus'

export default function homeData(data:any) {
  const store = useStore()
  const router = useRouter()
  const route = useRoute()

  const state = reactive({
    dataList: [] as Array<addFormInterface>,
  });
  let isShowAddDrawer = ref(false);

  onMounted(() => {
    const data = sessionStorage.getItem('dataList')
    if (data) {
      state.dataList = JSON.parse(data)
    } else {
      getListData();
    }
  })

  const getListData = async () => {
    try {
      data.loading.value = true
      const res = await api.getListApi()
      state.dataList = res.map((el: any) => ({
        name: el.userId,
        title: el.title,
        body: el.body,
        time: moment().format("YYYY-MM-DD HH:mm:ss"),
      }));
      addStorage()
    } catch (error) { 
    } finally {
      data.loading.value = false
    }
  }

  const onAdd = () => {
    isShowAddDrawer.value = true
  }

  const onDetail = (item: addFormInterface) => {
    store.commit("base/modify", item);
    router.push({
      name: "Detail",
    });
  }

  const onSubmit = (addForm: addFormInterface) => {
    state.dataList.unshift(addForm);
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
    addStorage()
    isShowAddDrawer.value = false;
  }

  const addStorage = () => {
    sessionStorage.setItem('dataList', JSON.stringify(state.dataList))
  }


  return {
    ...toRefs(state),
    isShowAddDrawer,
    getListData,
    onAdd,
    onDetail,
    onSubmit,
  }



}

